package com.shops.servlet.utils;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils {
    private static DataSource ds = null;
    private static final Logger logger = LoggerFactory.getLogger(JdbcUtils.class);
    static{
        Properties pro = new Properties();
        InputStream is= null;
        try {
            is = JdbcUtils.class.getResourceAsStream("C:\\shops_start\\resources\\db.properties");
            pro.load(is);
            ds = BasicDataSourceFactory.createDataSource(pro);
            String url = (String) pro.get("url");
            logger.info(url+"------------");
        }catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(is!=null) try{ is.close();}catch(Exception e){}
        }
    }

    private static Connection conn = null;

    private static final  ThreadLocal<Connection> tol = new ThreadLocal<>();

    public static Connection getConnection() {
        Connection conn = tol.get();
        if( conn==null ){
            try {
                conn = ds.getConnection();
                tol.set(conn);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
        }
        return conn;
    }

    public static void close(ResultSet rs, Statement stm, Connection conn){
        if(rs!=null) try{rs.close();}catch(Exception e){}
        if(stm!=null) try{stm.close();}catch(Exception e){}
        if(conn!=null) try{conn.close();  tol.remove(); }catch(Exception e){}
    }

    public static void close(){
        Connection conn = getConnection();
        if(conn!=null) try{conn.close();  tol.remove(); }catch(Exception e){}
    }
}
